package com.fs.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/code.do")
public class ValidateCodeServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req,resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("image/jpeg");//设置相应头ContentType类型
		ServletOutputStream out=resp.getOutputStream();//获取一个二进制输出流对象
		int width=60;
		int height=20;
		//创建缓冲图像
		BufferedImage imgbuf=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g=imgbuf.createGraphics();//创建一支画图的笔
		g.fillRect(0, 0, width, height);//设置图形的形状和高度
	
		g.setFont(new Font("Times News Roman",Font.PLAIN,18));//设置字体和字体大小
		//产生随机数0-9之间的4位数字
		String code="";
		Random r=new Random();//随机数对象
		//干扰线
	

		//干扰点
	
		
		String codes="0123456789";
		int index=codes.length();
		
		for(int i=0;i<8;i++){
			String rand=String.valueOf(codes.charAt(r.nextInt(index)));
			code+=rand;
			g.setColor(new Color(20+r.nextInt(110),20+r.nextInt(110),20+r.nextInt(110)));
			g.drawString(rand, 13*i+6,16);//画字符串
			
		}
		System.out.println("生成的随机数"+code);
		HttpSession session=req.getSession();
		session.setAttribute("code", code);
		ImageIO.write(imgbuf,"JPEG", out);
		out.close();
	}
	/*
	 * 获取指定范围的随机数颜色
	 */

}
